package com.cx.thread.message;

import java.util.LinkedList;
import java.util.Random;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.thread.message
 * @Description:
 * @Date 2025/5/26 16:31
 */

public class Producer {
    //发布者名称
    private String name;
    //对列或者集合  LinkedList便于插入删除
    private LinkedList<String> buffer;

    public Producer(String name, LinkedList<String> buffer) {
        this.name = name;
        this.buffer = buffer;
    }

    //发布消息
    public void produce(){
        //创建消息
        Random random = new Random();

        //发布消息
        synchronized (buffer){
            while (true){
                String message = "消息" + random.nextInt(1000);
                if(buffer.size() >= 10){
                    System.out.println(name +"等待阻塞");
                    try {
                        buffer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    buffer.add(message);
                    System.out.println(name + "添加消息" +message);
                    buffer.notifyAll(); //唤醒所有线程
                }
            }


        }



    }
}